package com.pzr.soccer.task.service;


import com.pzr.soccer.task.domain.Task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

@Service
@Slf4j
public class TaskService {

	@Autowired
	private ThreadPoolTaskScheduler threadPoolTaskScheduler;

	private ConcurrentHashMap<String, Future<?>> futrues = new ConcurrentHashMap<>();

	public void stopAllTasks() {
		for (Future<?> future : futrues.values()) {
			future.cancel(true);
			future = null;
		}
		futrues.clear();
		log.info("all stop");
	}

	public void stopTask(String taskId) {
		Future<?> future = futrues.get(taskId);
		if (future != null) {
			future.cancel(true);
			future = null;

			futrues.remove(taskId);
			log.info("stop: " + taskId);
		} else {
			log.warn("no such task! id=" + taskId);
		}
	}

	public void startATask(Runnable runnable, Task task) {
		// 先关掉已存在的
		if (futrues.get(task.getId()) != null) {
			futrues.get(task.getId()).cancel(true);
			futrues.remove(task.getId());
		}

		Future<?> future = threadPoolTaskScheduler.schedule(runnable,
				triggerContext -> new CronTrigger(task.getCron()).nextExecutionTime(triggerContext));

		log.info("add " + task.getId() + " task successfully!");
		futrues.put(task.getId(), future);

	}
	
	public List<String> getLiveTasksIds(){
		List<String> ids=new ArrayList<>();
		for(Entry<String, Future<?>> entry:this.futrues.entrySet()) {
			ids.add(entry.getKey());
		}
			
		return ids;
	}

}
